package com.central.apps.controller;

import com.central.app.service.HandlerService;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 采购接收接口类
 *
 * @author 李大超
 * @date 2022/10/9
 */
@RestController
public class PurchaseReceiptController {
    @Autowired
    private HandlerService handlerService;

    @PostMapping("/generateBarcode")
    public String generateBarcode(@RequestBody Map<String,Object> params) throws Exception {
        JSONObject json = new JSONObject();
        json.put("code", "0");
        String prtid = MapUtils.getString(params,"prtid");
        String poid = MapUtils.getString(params,"poid");
        String ids = MapUtils.getString(params,"ids");
        if (StringUtils.isEmpty(ids)) {
            json.put("msg", "请选择需要添加到条码管理的采购接收行信息!");
            return json.toString();
        }


        // 查询采购订单对应合同编号
        List<Map<String, Object>> poList = handlerService.findBySql("select ponum, concode from gq_po where id = " + poid);
        String ponum = "";
        String concode = "";

        if (CollectionUtils.isNotEmpty(poList)) {
            Map<String, Object> poMap = poList.get(0);
            ponum = (String) poMap.get("ponum");
            concode = (String) poMap.get("concode");
        }
        List<Map<String, Object>> bySql = handlerService.findBySql("select receiptnum,waremethod,status from gq_purchasereceipt where  id = " + prtid);
        Map<String, Object> map = bySql.get(0);
        String receiptnum = MapUtils.getString(map, "receiptnum");
        String waremethod = MapUtils.getString(map,"waremethod");
        String status = MapUtils.getString(map,"status");
        //20230331 需求手工入库也可以生成条码  app盘点时扫条码管理里的条码 根据物料编码匹配 扫一下加1
//        if("手工入库".equals(waremethod)){
//            json.put("code", "1");
//            json.put("msg", "入库方式需为扫码入库才可以生成条码");
//            return json.toString();
//        }
        if(!"已批准".equals(status)){
            json.put("code", "1");
            json.put("msg", "流程需已批准后，才可以生成条码");
            return json.toString();
        }
        // 查询采购接收行信息
        //List<Map<String, Object>> prtdlList = handlerService.findBySql("select * from gq_prtdetailline where prtid = " + prtid);
        List<Map<String, Object>> prtdlList = handlerService.findBySql("select * from gq_prtdetailline where id in (" + ids+")");
        StringBuffer id = new StringBuffer();
        List<Map<String, Object>> bclList= new ArrayList<>();
        for (Map<String, Object> prtdlMap : prtdlList) {
            Integer prtdlid = (Integer) prtdlMap.get("id");

            //获取验收字段，判断是否合格
            String insresults = (String)prtdlMap.get("insresults");
            String itemnum = MapUtils.getString(prtdlMap,"itemnum");
            if(!"合格".equals(insresults)){
                json.put("code", "1");
                json.put("msg", itemnum+"物料，检查结果不合格，无法生成条码");
                return json.toString();
            }
            String converttobc = MapUtils.getString(prtdlMap,"converttobc");
            if("1".equals(converttobc)){
                json.put("code", "1");
                //M1101100002等物料已经添加到条码, 请重新选择数据
                json.put("msg", itemnum+"物料已经添加到条码, 请重新选择数据");
                return json.toString();
            }


            Map<String, Object> bcMap = new HashMap<>();
            bcMap.put("batchnum", prtdlMap.get("batchnum"));
            bcMap.put("receiptnum", receiptnum);
            bcMap.put("manufacturer", prtdlMap.get("manufacturer"));
            bcMap.put("itemtype", prtdlMap.get("itemtype"));
            bcMap.put("concode", concode);
            bcMap.put("ponum", ponum);
            bcMap.put("itemnum", prtdlMap.get("itemnum"));
            bcMap.put("model", prtdlMap.get("model"));
            bcMap.put("expirydate", prtdlMap.get("expirydate"));
            bcMap.put("itemdesc", prtdlMap.get("itemdesc"));
            bcMap.put("prnum", prtdlMap.get("prnum"));
            bcMap.put("deptid", prtdlMap.get("deptid"));
            bcMap.put("deptcode", prtdlMap.get("deptcode"));
            bcMap.put("addtype","gq_prtdetailline");
            bcMap.put("addid",prtdlid);
            bcMap.put("receiptid",prtid);//采购接收id
            bcMap.put("waremethod",waremethod);//入库方式
            bcMap.put("receiveqty",prtdlMap.get("receiveqty"));//入库数量

            Object res = handlerService.insert("gq_barcode", bcMap);
            id.append(res).append(",");
            bcMap.put("id",res);
            //bcMap.put("expirydate",null);
            bcMap.put("productiondate",null);
            bclList.add(bcMap);
            // 更新标记字段
            handlerService.updateBySql("update gq_prtdetailline set converttobc = '1' where id = " + prtdlid);
        }

        json.put("msg", "添加到条码管理成功, 请到条码管理界面查询数据!");
        json.put("codeIds",id.toString());
        json.put("bclList",bclList);
        return json.toString();
    }

    @PostMapping("/acceptance")
    public String acceptance(@RequestBody Map<String,Object> params) throws Exception {

        String id = MapUtils.getString(params, "id");
        JSONObject json = new JSONObject();
        String sql = "select acceptments from gq_prtdetailline where prtid = " + id;
        List<Map<String, Object>> pulist = handlerService.findBySql(sql);
        if (CollectionUtils.isNotEmpty(pulist)) {
            String acceptments1="";
            for (int z = 0; z < pulist.size(); z++) {
                Map<String, Object> map = pulist.get(z);
                String acceptments = MapUtils.getString(map, "acceptments");
                acceptments1=acceptments1+acceptments;
            }

            if (!acceptments1.contains("04")) {
                json.put("code", "1");
                json.put("msg", "验证要求并非技术指标验证，无需进行采购验收流程！");
                return json.toString();
            } else {
                //accertificate:是否生成验收单
                List<Map<String, Object>> bySql = handlerService.findBySql("select receiptnum,accertificate,receiptdesc,createuserdesc from gq_purchasereceipt where id='" + id + "'");
                String accertificate1 = MapUtils.getString(bySql.get(0), "accertificate");
                if (!accertificate1.equals("0")){
                    json.put("code", "1");
                    json.put("msg", "已生成相关验收单，不能再次生成!");
                }else {
//                    String receiptnum = MapUtils.getString(bySql.get(0), "receiptnum");
//                    String receiptdesc = MapUtils.getString(bySql.get(0), "receiptdesc");
//                    String createuserdesc = MapUtils.getString(bySql.get(0), "createuserdesc");
//                    Map<String, Object> map2 = new HashMap<>();
//                    List<Map<String, Object>> list = handlerService.findBySql("select * from gq_puraccept order by createtime desc limit 1");
//                    int xuhao;
//                    if (CollectionUtils.isEmpty(list)){
//                        xuhao= 1001;
//                    }else {
//                        xuhao = Integer.valueOf(list.get(0).get("accertificate").toString().replace("CDPY", "")) + 1;
//                    }
//
//                    String accertificate = "CDPY0000" + xuhao;//验收单号
//                    map2.put("receiptnum", receiptnum);
//                    map2.put("accertificatedesc",receiptdesc);
//                    map2.put("requireddate", new Date());
//                    map2.put("accertificate", accertificate);
//                    map2.put("status", "新建");
//                    map2.put("receiptnumid",id);
//                    map2.put("createuserdesc",createuserdesc);
//                    map2.put("deptcode", bySql.get(0).get("deptcode"));
//                    handlerService.insert("gq_puraccept", map2);//添加到采购验收主表

                    String sql1 = "select * from gq_prtdetailline where prtid = '" + id + "'and acceptments  like '%04%'";//根据采购接收主表id查询采购订单汇总行数据
                    List<Map<String, Object>> prlist = handlerService.findBySql(sql1);
                    if (CollectionUtils.isNotEmpty(prlist)) {
                        for (Map<String, Object> stringObjectMap : prlist) {
                            String receiptnum = MapUtils.getString(bySql.get(0), "receiptnum");
                            String receiptdesc = MapUtils.getString(bySql.get(0), "receiptdesc");
                            String username = MapUtils.getString(stringObjectMap, "username");
                            String usernameid = MapUtils.getString(stringObjectMap, "usernameid");
                            String nickname = MapUtils.getString(stringObjectMap, "nickname");
                            Map<String, Object> map2 = new HashMap<>();
                            List<Map<String, Object>> list = handlerService.findBySql("select * from gq_puraccept order by createtime desc limit 1");
                            int xuhao;
//                            if (CollectionUtils.isEmpty(list)){
//                                xuhao= 1001;
//                            }else {
//                                xuhao = Integer.valueOf(list.get(0).get("accertificate").toString().replace("CDPY", "")) + 1;
//                            }
                            Map<String, Object> poMap = new HashMap<>();
                            handlerService.addBizNum("puracceptApp","gq_puraccept",poMap);
                            String accertificate = (String) poMap.get("accertificate");
//                            String accertificate = "CDPY0000" + xuhao;//验收单号
                            map2.put("receiptnum", receiptnum);
                            map2.put("applicant",stringObjectMap.get("applicant"));
                            map2.put("accertificatedesc",receiptdesc);
                            map2.put("requireddate", new Date());
                            //获取未来十天时间
                            Date date = new Date();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String format = simpleDateFormat.format(date);
                            Calendar instance = Calendar.getInstance();
                            instance.add(Calendar.DATE,10);
                            String format1 = simpleDateFormat.format(instance.getTime());
                            Date parse = simpleDateFormat.parse(format1);
                            //未来十天时间
                            map2.put("expetime",parse);
                            map2.put("accertificate", accertificate);
                            map2.put("status", "新建");
                            map2.put("receiptnumid",id);

                            map2.put("createuser",usernameid);
                            map2.put("createuserdesc",nickname);
                            map2.put("deptcode", bySql.get(0).get("deptcode"));
                            handlerService.insert("gq_puraccept", map2);//添加到采购验收主表
                            Map<String, Object> map1 = new HashMap<>();
                            map1.put("itemnum", stringObjectMap.get("itemnum"));
                            map1.put("itemdesc", stringObjectMap.get("itemdesc"));
                            map1.put("unit", stringObjectMap.get("orderunit"));
                            map1.put("qualquantity", stringObjectMap.get("arrquantity"));
                            map1.put("prtsummarylineid", stringObjectMap.get("id"));
                            map1.put("applicant",stringObjectMap.get("applicant"));
                            //map1.put("receiveqty",stringObjectMap.get("qualquantity"));
                            map1.put("accertificate", accertificate);
                            map1.put("isdpaanalysis", stringObjectMap.get("isdpaanalysis"));
                            map1.put("specialrequirements", stringObjectMap.get("specialrequirements"));
                            map1.put("maintechtors", stringObjectMap.get("maintechtors"));
                            map1.put("prtid", stringObjectMap.get("prtid"));
                            map1.put("applyby",stringObjectMap.get("applyby"));
                            handlerService.insert("gq_puracceptline", map1);
                            handlerService.updateBySql("update gq_prtdetailline set accertificate=1 where prtid='"+stringObjectMap.get("prtid")+"'");
                        }
                    }
                    String status="验收中";
                    handlerService.updateBySql("update gq_purchasereceipt set status ='"+status+"' where id='"+id+"'");
                    handlerService.updateBySql("update gq_purchasereceipt set accertificate= 1 where id='" + id + "'");
                    json.put("code", "0");
                    json.put("msg", "添加到采购验收成功, 请到采购验收界面查询数据!");
                }
            }


        }

        return json.toString();
    }
}
